package cloud.netflix.feign;

import java.util.List;

import feign.Feign;
import feign.Logger;
import feign.Param;
import feign.RequestLine;
import feign.Response;
import feign.codec.Decoder;
import feign.codec.ErrorDecoder;
import feign.gson.GsonDecoder;

public class GitHubExample {

	static class Contributor {
		String login;
		int contributions;
	}

	static class GitHubClientError extends RuntimeException {
		private String message;

		@Override
		public String getMessage() {

			return message;
		}
	}

	static class GitHubErrorDecoder implements ErrorDecoder {

		final Decoder decoder;
		final ErrorDecoder defaultDeocder = new ErrorDecoder.Default();

		public GitHubErrorDecoder(Decoder decoder) {
			this.decoder = decoder;
		}

		@Override
			public Exception decode(String methodKey, Response response) {
				try {
					return (Exception) decoder.decode(response, GitHubClientError.class);
				} catch (Exception e) {
					return defaultDeocder.decode(methodKey,response);
				}
			}
	}

	interface GitHub {
		@RequestLine("GET /repos/{owner}/{repo}/contributors")
		List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
	}

	public static void main(String[] args) {
		Decoder decoder = new GsonDecoder();
		GitHub gitHub = Feign.builder().decoder(decoder)
				.errorDecoder(new GitHubErrorDecoder(decoder))
				.logger(new Logger.ErrorLogger())
				.logLevel(Logger.Level.BASIC)
				.target(GitHub.class, "https://api.github.com");
		
		System.out.println("Let's fetch and print a list of the contributors to this library.");
		List<Contributor> contributors = gitHub.contributors("netflix", "feign");
		for (Contributor contributor : contributors) {
			System.out.println(contributor.login + "("+contributor.contributions+")");
		}
		
		System.out.println("Now, let's cause an error.");
		try {
			gitHub.contributors("netflix", "some-unknown-project");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
		
	}

}
